<?php
define('ELF_HASH_LENGTH', 15);

class ElfSecurity {
  function pwdHash($pwd, $salt = null) {
    if(empty($salt)) $salt = $this->randStr(ELF_HASH_LENGTH);
    if(strlen($salt) < ELF_HASH_LENGTH) {
      $salt .= $this->randStr(ELF_HASH_LENGTH - strlen($salt));
    }
    return $salt . crypt($pwd, $salt);
  }

  function checkPwd($pwd, $hashed) {
    return hash_equals($hashed, $this->pwdHash($pwd, substr($hashed, 0, ELF_HASH_LENGTH)));
  }

  function randStr($len, $dic = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
    $result ='';
    for ($i = 0; $i < $len; $i++) { 
      $result .= $dic[rand() % strlen($dic)];
    }
    return $result;
  }
}
